﻿/*
 * User: Masy Freddy
 * Date: 15/09/2011
 * Time: 17:08
 */
namespace MetaVideoEditorEvolved.AddIn.AddInAdapters
{
	using System;
	using System.Threading;

	internal class AppDispatcher
	{
		private System.Windows.Application app;
		private string eventName = "appStarted:";
		private EventWaitHandle appStarted;
		private Thread myThread;
		private static AppDispatcher dispatcher;
		
		public static AppDispatcher Current
		{
			get
			{
				return dispatcher = dispatcher ?? new AppDispatcher();
			}
		}

		private AppDispatcher()
		{
			appStarted = new EventWaitHandle(false, EventResetMode.ManualReset, eventName);
			
			ThreadStart ts =
				new ThreadStart(
					delegate()
					{
						if (System.Windows.Application.Current == null)
						{
							app = new System.Windows.Application();
							myThread = Thread.CurrentThread;
							appStarted.Set();
							appStarted.Close();
							app.Run();
						}
						else
						{
							app = System.Windows.Application.Current;
							appStarted.Set();
							appStarted.Close();
						}
					}
				);
			
			Thread t = new Thread(ts);
			t.SetApartmentState(ApartmentState.STA);
			t.Start();
			appStarted.WaitOne();
		}

		public void DoWork(Worker d)
		{
			if (!Thread.CurrentThread.Equals(myThread))
			{
				app.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, d);
			}
			else
			{
				d.Invoke();
			}
		}
	}

	delegate void Worker();
}
